package com.tongtong.config.filter;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author zl
 */
public class ApiHandlerInterceptor implements AsyncHandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final Cache<String, Object> cacheThread = CacheBuilder.newBuilder()
            // 设置缓存在写入10秒钟之后自动失效
            .expireAfterWrite(10, TimeUnit.SECONDS)
            // 设置并发级别为10
            .concurrencyLevel(10)
            // 开启缓存统计
            .recordStats()
            .build();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
       /* if(WebConstants.API.contains(request.getRequestURI())){
            return true;
        }*/
        /*String token = request.getHeader(WebConstants.TOKEN);
        if(Objects.isNull(token)){
            throw new RuntimeException("请登录!!");
        }
        if(JWTUtils.verify(token)){
            throw new RuntimeException("token失效，请重新登录!!");
        }
        String account = JWTUtils.getTokenInfo(token);
        WebThreadLocal.setUser(account);*/

        /*String phone = request.getParameter("phone");
        if(StringUtils.isEmpty(phone) || Objects.equals(phone, WebConstants.UNDEFINED)){
            return false;
        }
        SimPhone iccidByPhone = null;
        Object ifPresent = cacheThread.getIfPresent(phone);
        if(Objects.isNull(ifPresent)){
            iccidByPhone = simPhoneService.getIccidByPhone(phone);
            if(Objects.isNull(iccidByPhone)){
                return false;
            }
            cacheThread.put(phone,iccidByPhone);
        }else{
            iccidByPhone = (SimPhone) ifPresent;
        }
        WebThreadLocal.setSimPhone(iccidByPhone);*/
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        WebThreadLocal.remove();
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        logger.info("请求地址为：{}",request.getRequestURI());
        logger.info("请求耗时:{} " , (endTime - startTime));
    }


}
